<template>
  <div class="form" v-show="showLoginLayer">
    <h2>登录</h2>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        required
        placeholder="输入用户名或手机号"
        :rules="[{ required: true }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        required
        placeholder="输入密码"
        :rules="[{ required: true}]"
      />
      <div style="margin: 16px;">
        <van-button color="#14405B" round block type="info" :loading="loading" native-type="submit">
          登录
        </van-button>
      </div>
      <span class="tip">{{tip}}</span>
    </van-form>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import {getLoginInfo} from "../api";

export default {
  name: 'Login',
  props: {
    productId: Number
  },
  data () {
    return {
      username: '', // 用户名
      password: '', // 密码
      loading: false, // 加载loading
      tip: '提示：请输入人才市场注册的账号密码' // 提示
    }
  },
  computed: {
    ...mapState({
      showLoginLayer: state => state.showLoginLayer
    })
  },
  methods: {
    // 提交登陆表单
    onSubmit (values) {
      this.loading = true
      getLoginInfo(values).then(res => {
        this.loading = false
        // 登陆成功
        if (res) {
          this.Dialog.alert({
            title: '登陆成功',
            message: '去支付'
          }).then(() => {
            this.$store.dispatch('changeLoginLayerState', false) // 关闭登陆框
            this.$store.dispatch('changePayLayerState', true) // 打开支付框Pay.vue
            sessionStorage.setItem('apiToken', res.api_token) // 保存登陆信息到sessionStorage
          }).catch(err => {
            console.log(err)
          })
        } else {
          // 登陆失败
          this.Toast('登陆失败')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.form {
  width: 80%;
  padding: 10px 0;

  h2 {
    font-size: 16px;
    text-align: center;
    padding: 15px 0;
  }
}

.tip {
  display: block;
  color: #909399;
  font-size: 14px;
  text-align: center;
}
</style>
